package com.civ.sensor.dht.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.civ.util.gpiotools.GpioUnit;
import com.pi4j.io.gpio.GpioPinDigitalMultipurpose;
import com.pi4j.io.gpio.PinMode;

/**
 * gpio控制器
 * @author zhengxl
 *
 */
public class ControlGpio {
	public static int GPIO_RELAY1 = 5;
	public static int GPIO_RELAY2 = 6;
	public static int GPIO_RELAY3 = 7;
	public static int GPIO_RELAY4 = 8;
	
	public static Map<String, String> gpio(String cmd, int gpioid, String now) {
		cmd = cmd == null ? "" : cmd;
		String gid = gpioid >=10 ? "GPIO_"+gpioid : "GPIO_0"+gpioid;
		now = now == null ? "" : now;
		GpioPinDigitalMultipurpose gpio = GpioUnit.getInstance()
				.getGpioPinDigitalMultipurpose(gid);
		Map<String, String> jmap = new HashMap<>();
		switch (cmd) {
		case "get":
			if (gpio != null) {
				jmap.put("code", "0");
				jmap.put("message", "success");
				jmap.put("mode", gpio.getMode().toString());
				jmap.put("state", gpio.getState().toString());
			} else {
				jmap.put("code", "-1");
				jmap.put("message", "出现错误");
			}
			break;

		case "setmode":
			if (gpio != null) {

				if (now.equals("输入")) {
					gpio.setMode(PinMode.DIGITAL_OUTPUT);
				}
				if (now.equals("输出")) {
					gpio.setMode(PinMode.DIGITAL_INPUT);
				}
				if (now.equals("未知")) {
					gpio.setMode(PinMode.DIGITAL_OUTPUT);
				}

				jmap.put("code", "0");
				jmap.put("message", "success");
				jmap.put("mode", gpio.getMode().toString());
				jmap.put("state", gpio.getState().toString());

			} else {
				jmap.put("code", "-1");
				jmap.put("message", "出现错误");
			}
			break;

		case "setstate":
			if (gpio != null) {

				if (now.equals("低电平")) {
					gpio.high();
				}
				if (now.equals("高电平")) {
					gpio.low();
				}
				if (now.equals("未知")) {
					gpio.high();
				}

				jmap.put("code", "0");
				jmap.put("message", "success");
				jmap.put("mode", gpio.getMode().toString());
				jmap.put("state", gpio.getState().toString());
			} else {
				jmap.put("code", "-1");
				jmap.put("message", "出现错误");
			}
			break;

		case "getall":

			Iterator iter = GpioUnit.getInstance().getGpioMap().entrySet()
					.iterator();
			jmap.put("code", "0");
			jmap.put("message", "success");

			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String gpioname = (String) entry.getKey();
				GpioPinDigitalMultipurpose pin = (GpioPinDigitalMultipurpose) entry
						.getValue();

				if (pin != null) {
					jmap.put("gpioname", gpioname);
					jmap.put("mode", gpio.getMode().toString());
					jmap.put("state", gpio.getState().toString());

				} else {
					jmap.put("gpioname", gpioname);
					jmap.put("mode", "UNKNOW");
					jmap.put("state", "UNKNOW");

				}
			}
			break;

		default:
			jmap.put("code", "-1");
			jmap.put("message", "无法解析意图");
		}
		return jmap;
	}

}
